package com.yang.strategy.context;


import com.yang.enums.CacheStrategyEnum;
import com.yang.strategy.CacheStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 * 缓存策略上下文
 * </p>
 * @author yang
 * @date 2023/7/23
 */
@Service
public class CacheStrategyContext {

    @Autowired
    private Map<String, CacheStrategy> cacheStrategyMap;

    public <R, ID> R executeCacheStrategy(String keyPrefix,
                                          ID id,
                                          Class<R> type,
                                          Function<ID, R> dbFallback,
                                          Long time,
                                          TimeUnit unit,
                                          CacheStrategyEnum cacheStrategyEnum){

        CacheStrategy cacheStrategy = cacheStrategyMap.get(cacheStrategyEnum.getStrategy());

        return cacheStrategy.getCache(keyPrefix,id,type,dbFallback,time,unit);
    }
}
